<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <template #before>
          <span slot="before">共{{ total }}条记录</span>
        </template>
        <template slot="after">
          <el-button size="small" type="warning" @click="$router.push('/employees/import?type=user')">导入</el-button>
          <el-button size="small" type="danger" @click="handleDownload">导出</el-button>
          <el-button size="small" type="primary" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card v-loading="loading">
        <el-table border :data="list">
          <el-table-column label="序号" type="index" :index="indexFn" width="80" sortable="" />
          <el-table-column label="头像" align="center" width="130">
            <template slot-scope="{row}">
              <img v-imageerror="row.staffPhoto" :src="row.staffPhoto" style="border-radius: 50%; width: 100px; height: 100px; padding: 10px" alt="" @click="showQrCode(row.staffPhoto)">
            </template>
          </el-table-column>
          <el-table-column label="姓名" prop="username" width="150" sortable="" />
          <el-table-column label="手机号" prop="mobile" width="140" sortable="" />
          <el-table-column label="工号" prop="workNumber" width="100" sortable="" />
          <el-table-column label="聘用形式" :formatter="formatEmployment" width="110" sortable="" />
          <el-table-column label="部门" :formatter="formatDepartmentName" width="100" sortable="" />
          <el-table-column label="入职时间" width="170" sortable="">
            <template #default="{row}">
              {{ row.timeOfEntry | dateFormat }}
            </template>
          </el-table-column>
          <el-table-column label="是否在职" :formatter="formatInServiceStatus" width="110" sortable="" />
          <el-table-column label="账户状态" width="110" sortable="">
            <template #default="{row}">
              <el-switch
                :value="row.enableState === 1"
                active-color="#13ce66"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)">角色</el-button>
              <!-- !checkPermission('EMPLOYEES_DEL') ||  enVisible-->
              <el-button :disabled="!checkPermission('EMPLOYEES_DEL')" type="text" size="small" class="asd" @click="deleteEmployee(row.id)">删除</el-button>
              <!-- <el-button :disabled="!(checkPermission('EMPLOYEES_DEL') && enVisible)" type="text" size="small" class="asd" @click="deleteEmployee(row.id)">删除</el-button> -->
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :current-page="query.page"
            :page-sizes="[10, 20, 30, 40, 50, 100]"
            :page-size="query.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            hide-on-single-page
            @size-change="changeSize"
            @current-change="changePage"
          />
        </el-row>
      </el-card>
      <add-employee :show-dialog.sync="showDialog" />
      <el-dialog title="二维码" :visible.sync="showCodeDialog">
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>
      <assign-role ref="assignRole" :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
    </div>
  </div>
</template>

<script>
import QrCode from 'qrcode'
import dayjs from 'dayjs'
// import { mapGetters } from 'vuex'
import { getEmployeeList, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/api/constant/employees'
import AddEmployee from './components/add-employee.vue'
import AssignRole from './components/assign-role.vue'
// import { getPermissionList } from '@/api/permissions'
// // import { transArray2Tree } from '@/utils/'

export default {
  name: 'Employees',
  components: {
    AddEmployee,
    AssignRole
  },
  data() {
    return {
      query: {
        page: 1,
        size: 10
      },
      list: [],
      total: 0,
      loading: false,
      showDialog: false,
      showCodeDialog: false,
      showRoleDialog: false,
      userId: '',
      enVisible: false
    }
  },
  // computed: {
  //   ...mapGetters(['roles'])
  // },
  created() {
    this.getEmployeeList()
  },
  methods: {
    async getEmployeeList() {
      this.loading = true
      const { rows, total } = await getEmployeeList(this.query)
      // console.log(await getEmployeeList(this.query))
      // const permissionsList = (await getPermissionList()).filter(item => item.type !== 3)
      // console.log(permissionsList)
      // const [{ id }] = permissionsList.filter(item => item.code === 'employees')

      // const [{ enVisible }] = permissionsList.filter(item => item.pid === id && item.code === 'EMPLOYEES_DEL')
      // console.log(enVisible)
      // console.log((enVisible !== 0))
      // console.log(this.checkPermission('EMPLOYEES_DEL'))

      // this.enVisible = (enVisible !== 0)

      // console.log((await getPermissionList()).filter(item => item.type !== 3 && item.code === 'employees'))

      // console.log(transArray2Tree((await getPermissionList()).filter(item => item.type !== 3), '0'), 111)

      this.list = rows
      this.total = total
      this.loading = false
    },
    indexFn(index) {
      return (this.query.page - 1) * this.query.size + (index + 1)
    },
    changeSize(size) {
      this.query.page = 1
      this.query.size = size
      this.getEmployeeList()
    },
    changePage(page) {
      this.query.page = page
      this.getEmployeeList()
    },
    formatEmployment(row) {
      const o = EmployeeEnum.hireType.find(item => +item.id === +row.formOfEmployment)
      return o ? o.value : '未知'
    },
    formatInServiceStatus(row) {
      const o = EmployeeEnum.workingState.find(item => +item.id === +row.inServiceStatus)
      return o ? o.value : '未知'
    },
    formatDepartmentName(row) {
      return row.departmentName ? row.departmentName : '未知'
    },
    async deleteEmployee(id) {
      // await delEmployee(id)
      // this.getEmployeeList()

      try {
        await this.$confirm('您确定删除该员工吗? ')
        await delEmployee(id)
        if (this.list.length === 1 && this.query.page > 1) {
          this.query.page--
        }
        this.getEmployeeList()
        this.$message.success('删除成功! ')
      } catch {
        // ...
      }
    },
    handleDownload() {
      import('@/vendor/Export2Excel').then(async r => {
        const { rows } = await getEmployeeList({
          page: 1,
          size: this.total
        })
        // console.log(rows)

        const headersRelations = {
          姓名: 'username',
          手机号: 'mobile',
          入职日期: 'timeOfEntry',
          聘用形式: 'formOfEmployment',
          转正日期: 'correctionTime',
          工号: 'workNumber',
          部门: 'departmentName'
        }

        // keys和values 单独出现时他们是无序的  当keys 和 values 同时出现的时 他们的顺序一定是一一对应的
        const header = Object.keys(headersRelations)
        const values = Object.values(headersRelations)

        const data = []
        rows.forEach(item => {
          const arr = []
          for (let i = 0; i < values.length; i++) {
            const key = values[i]
            let v = item[key]
            if (key === 'timeOfEntry' || key === 'correctionTime') {
              v = dayjs(v).format('YYYY/MM/DD')
            } else if (key === 'formOfEmployment') {
              const o = EmployeeEnum.hireType.find(item => +item.id === +v)
              v = o ? o.value : '未知'
            } else if (key === 'departmentName') {
              v = v || '未知'
            }
            arr.push(v)
          }
          data.push(arr)
        })

        // 与上面等价
        // const header = ['姓名', '手机号', '入职日期', '聘用形式', '转正日期', '工号', '部门']
        // const data = rows.map(item => {
        //   const { username, mobile, timeOfEntry, formOfEmployment, correctionTime, workNumber, departmentName } = item
        //   return [username, mobile, timeOfEntry, formOfEmployment, correctionTime, workNumber, departmentName]
        // })

        r.export_json_to_excel({
          // #3 准备表头，必填
          header,
          // #4 准备具体数据，必填
          data,
          // #5 文件名，非必填
          filename: '学生信息表',
          // #6 列宽是否自适应，非必填
          autoWidth: true,
          // #7 文件后缀名，非必填
          bookType: 'xlsx'
        })
      })
    },
    showQrCode(url) {
      if (!url) return this.$message.warning('该用户还未上传头像')
      this.showCodeDialog = true
      this.$nextTick(() => {
        QrCode.toCanvas(this.$refs.myCanvas, url)
      })
    },
    async editRole(id) {
      // this.userId = id
      // this.$nextTick(() => {
      //   this.$refs.assignRole.getUserDetailById()
      // })
      // this.$nextTick(this.$refs.assignRole.getUserDetailById)
      // this.$nextTick().then(() => {
      //   this.$refs.assignRole.getUserDetailById()
      // })

      // await this.$refs.assignRole.getUserDetailById(id)
      // this.showRoleDialog = true
      this.showRoleDialog = true
      this.userId = id
      await this.$refs.assignRole.getUserDetailById(id)
    }
    // checkPermission(key) {
    // // 为什么加 ? 号
    // // 点击退出，快捷访问中的 `roles: state => state.user.userInfo.roles`
    // // userInfo 是空对象，所以 userInfo.roles 是 undefined
    // // 如果退出的页面用到了这个 checkPermission 方法，下面的代码会报错
    // // this.$store.getters.roles.points 会报错
    // // 所以...
    //   const points = this.roles?.points
    //   // 新添加的用户的 points 可能是 null
    //   if (points && points.length) {
    //     return points.includes(key)
    //   }
    //   return false
    // }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-loading-mask{
  z-index: 1999;
}

</style>
